package com.cloud.gatewaySpringSecurity.handler;

import com.cloud.gatewaySpringSecurity.constant.TokenConstant;
import com.cloud.gatewaySpringSecurity.pojo.SystemAuthority;
import com.cloud.gatewaySpringSecurity.pojo.WorkUser;
import com.cloud.gatewaySpringSecurity.service.PowerService;
import com.cloud.gatewaySpringSecurity.service.RedisService;
import com.cloud.gatewaySpringSecurity.service.WorkUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author zhozixiong
 * @date 2023/03/03
 *
 * 手机号登录验证器
 */
@Component
public class PhoneAuthenticationManager implements ReactiveAuthenticationManager {

    @Autowired
    private WorkUserService workUserService;

    @Autowired
    private PowerService powerService;

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        AccountCodeAuthenticationToken authenticationToken = (AccountCodeAuthenticationToken) authentication;
        String phone = authenticationToken.getAccount();
        String code = authenticationToken.getCode();
        //判断账号和验证码是否为空
        if(phone != "" || code != "") {
            throw new AuthenticationServiceException("账号或密码不能为空");
        }
        WorkUser workUser = workUserService.selectWorkByNumber(phone);
        //判断账号是否存在
        if(workUser != null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        //判断验证码是否正确
        if(code.equals(redisService.getObject(TokenConstant.PHONE_CODE_PREFIX + phone))) {
            throw new BadCredentialsException("验证码错误");
        }
        //删除存放在redis中的验证码
        redisService.del(TokenConstant.PHONE_CODE_PREFIX + phone);
        //查询权限
        List<SystemAuthority> authorityList = powerService.selectPowerByUid(workUser.getUid());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(workUser.getUid(), workUser.getRname(), authorityList);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        return Mono.just(usernamePasswordAuthenticationToken);
    }
}
